package com.ecoolex.chinadutyfree.retailer.core.manager;

import java.time.Instant;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.chinadutyfree.retailer.core.dao.StoreDAO;
import com.ecoolex.chinadutyfree.retailer.entity.Store;
import com.ecoolex.chinadutyfree.retailer.entity.Store.Column;
import com.ecoolex.chinadutyfree.retailer.entity.StoreExample;
import com.ecoolex.chinadutyfree.retailer.entity.StoreExample.Criteria;
import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;

@Service
public class StoreManager {
	
    @Autowired
    private StoreDAO dao;
    
    public Store get(String storeId) {
    	StoreExample example = new StoreExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andStoreIdEqualTo(storeId).andDeletedEqualTo(Store.NOT_DELETED);
		return dao.selectOneByExample(example);
	}
    
    public Pagination<Store> queryStore(Page page) {
    	StoreExample example = new StoreExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andDeletedEqualTo(Store.NOT_DELETED);
    	example.setOffset(page.getFirstIndex());
    	example.setRows(page.getPageSize());
		return Pagination.create(page, 
			dao.countByExample(example),
			() -> dao.selectByExample(example));
	}

	public Store addStore(Store record, String createUser){
		StoreExample example = new StoreExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andDeletedEqualTo(Store.NOT_DELETED);
    	long count = dao.countByExample(example);
		BizAssert.isTrue(Check.isLessThan(count, 1L),ResultCode.VERIFY.build(10), "已经存在商户信息");
		record.setDeleted(Store.NOT_DELETED);
		record.setCreateUser(createUser);
		record.setCreateTime(Date.from(Instant.now()));
		record.setUpdateUser(createUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.insert(record);
		return record;
	}

	public Store editStore(Store record, String updateUser){
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.excludes(
			Column.deleted,
			Column.createUser,
			Column.createTime));
		return record;
	}

	public Store editStorePartInfo(Store record, String updateUser){
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.excludes(
			Column.type,
			Column.externalStoreId,
			Column.homePageUrl,
			Column.detailUrl,
			Column.serviceId,
			Column.deleted,
			Column.createUser,
			Column.createTime));
		return record;
	}
}